<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>订单填写</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #0a2342, #1e3c72);
            color: #fff;
            font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
        }
        .container {
            padding: 2rem;
            max-width: 960px;
        }
        .card {
            background: rgba(255, 255, 255, 0.08);
            border-radius: 1rem;
            padding: 2rem;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(12px);
        }
        .form-label, .card-title {
            color: #ffd54f;
            font-weight: bold;
        }
        .form-control, select {
            background: rgba(255, 255, 255, 0.15);
            border: none;
            color: #fff;
            border-radius: 0.75rem;
        }
        .form-control::placeholder {
            color: rgba(255, 255, 255, 0.7);
        }
        .btn {
            border-radius: 2rem;
            font-weight: bold;
        }
        .amount-box {
            font-size: 1.5rem;
            text-align: right;
            margin-top: 2rem;
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid #ffd54f;
            padding: 1rem;
            border-radius: 1rem;
            box-shadow: 0 0 20px #ffd54f88, 0 0 35px #ffd54f55;
        }
        .passenger-block {
            background: rgba(255,255,255,0.06);
            border: 1px solid rgba(255,255,255,0.15);
            border-radius: 1rem;
            padding: 1rem;
            margin-bottom: 1rem;
            box-shadow: 0 10px 25px rgba(0,0,0,0.3);
        }
    </style>
</head>
<body>

<div class="container">
    <div class="card">
        <h2 class="card-title mb-4"><i class="bi bi-ticket-detailed-fill me-2"></i>填写订单</h2>

        <form method="post"  id="orderForm">
            <input type="hidden" id="flightId" name="flightId" th:value="${flightId}"/>
            <!-- ✅ 新增隐藏字段用于重定向参数 -->
            <input type="hidden" id="departureCity" th:value="${departureCity}" />
            <input type="hidden" id="arrivalCity" th:value="${arrivalCity}" />
            <input type="hidden" id="departureDate" th:value="${departureDate}" />
            <input type="hidden" id="returnDate" th:value="${returnDate}" />
            <input type="hidden" id="roundTrip" th:value="${roundTrip}" />
            <div class="mb-3">
                <label class="form-label">订单编号</label>
                <input type="text" id="orderNo" name="orderNo" class="form-control" readonly>
            </div>
            <div class="mb-3">
                <label class="form-label">航班号</label>
                <input type="text" name="flightNo" class="form-control" th:value="${flightNo}" readonly>
            </div>
            <div class="mb-3">
                <label class="form-label">出发机场</label>
                <input type="text" name="depPort" class="form-control" th:value="${depPort}" readonly>
            </div>
            <div class="mb-3">
                <label class="form-label">到达机场</label>
                <input type="text" name="arrPort" class="form-control" th:value="${arrPort}" readonly>
            </div>

            <div id="passengerContainer"></div>

            <button type="button" class="btn btn-warning mt-3" id="addPassengerBtn">
                ➕ 添加乘客
            </button>

            <div class="amount-box">
                总金额：<span id="totalAmount">￥0.00</span>
            </div>

            <button type="submit" class="btn btn-success mt-4 w-100">
                🧾 提交订单
            </button>
        </form>
    </div>
</div>

<script>
    const basePrice = [[${basePrice}]];
    let passengerIndex = 0;
    const seatClassMap = {
        '1': 1,
        '2': 2,
        '3': 3
    };

    // 用于存储已被选中的座位号（全局）
    const selectedSeats = new Set();

    function generateOrderNo() {
        const now = new Date();
        return 'ORD' + now.getFullYear() + (now.getMonth() + 1).toString().padStart(2, '0') +
            now.getDate().toString().padStart(2, '0') +
            now.getHours().toString().padStart(2, '0') +
            now.getMinutes().toString().padStart(2, '0') +
            now.getSeconds().toString().padStart(2, '0') +
            Math.floor(Math.random() * 1000);
    }

    function updateTotalAmount() {
        let total = 0;
        document.querySelectorAll('.passenger-block').forEach(block => {
            const cabin = block.querySelector('.cabin-select').value;
            let price = basePrice;
            if (cabin === '2') price += 50;
            if (cabin === '3') price += 200;
            block.querySelector('.amount-input').value =  price.toFixed(2);
            total += price;
        });
        document.getElementById('totalAmount').innerText = '￥' + total.toFixed(2);
    }

    // 重新渲染所有座位选项，禁用已被选的座位（除了当前select自己选的座位）
    function refreshAllSeatOptions() {
        const blocks = document.querySelectorAll('.passenger-block');
        blocks.forEach(block => {
            const seatSelect = block.querySelector('.seat-select');
            const currentSelected = seatSelect.value; // 当前乘客已选座位号
            const cabin = block.querySelector('.cabin-select').value;
            const flightId = document.getElementById('flightId').value;
            const seatClassId = seatClassMap[cabin];

            if (!seatClassId) {
                seatSelect.innerHTML = '<option value="">请选择座位</option>';
                return;
            }

            fetch(`/order/available?flightId=${flightId}&seatClassId=${seatClassId}`)
                .then(res => res.json())
                .then(seats => {
                    seatSelect.innerHTML = '<option value="">请选择座位</option>';
                    seats.forEach(seat => {
                        const opt = document.createElement('option');
                        opt.value = seat;
                        opt.textContent = seat;
                        if (selectedSeats.has(seat) && seat !== currentSelected) {
                            opt.disabled = true;
                            opt.textContent += '（已选）';
                        }
                        seatSelect.appendChild(opt);
                    });
                    seatSelect.value = currentSelected || "";
                })
                .catch(err => {
                    console.error('加载座位失败', err);
                    seatSelect.innerHTML = '<option value="">加载失败</option>';
                });
        });
    }

    function fetchAvailableSeats(cabinType, block) {
        const flightId = document.getElementById('flightId').value;
        const seatClassId = seatClassMap[cabinType];
        const seatSelect = block.querySelector('.seat-select');

        if (!seatClassId) {
            seatSelect.innerHTML = '<option value="">请选择座位</option>';
            return;
        }

        fetch(`/order/available?flightId=${flightId}&seatClassId=${seatClassId}`)
            .then(res => res.json())
            .then(seats => {
                seatSelect.innerHTML = '<option value="">请选择座位</option>';
                seats.forEach(seat => {
                    const opt = document.createElement('option');
                    opt.value = seat;
                    opt.textContent = seat;
                    if (selectedSeats.has(seat)) {
                        opt.disabled = true;
                        opt.textContent += '（已选）';
                    }
                    seatSelect.appendChild(opt);
                });
            })
            .catch(err => {
                console.error('加载座位失败', err);
                seatSelect.innerHTML = '<option value="">加载失败</option>';
            });
    }

    function addPassengerBlock() {
        const container = document.getElementById('passengerContainer');
        const index = passengerIndex++;
        const block = document.createElement('div');
        block.className = 'passenger-block';
        block.innerHTML = `
        <div class="row g-3 align-items-end">
            <div class="col-md-3">
                <label class="form-label">姓名</label>
                <input type="text" name="passengers[${index}].fullName" class="form-control" required>
            </div>
            <div class="col-md-2">
                <label class="form-label">性别</label>
                <select name="passengers[${index}].gender" class="form-control" required>
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">身份证</label>
                <input type="text" name="passengers[${index}].idNo" class="form-control" minlength="18" maxlength="18" required>
            </div>
            <div class="col-md-2">
                <label class="form-label">电话</label>
                <input type="text" name="passengers[${index}].phone" class="form-control" minlength="11" maxlength="11" required>
            </div>
            <div class="col-md-2">
                <label class="form-label">仓位</label>
                <select name="passengers[${index}].cabin" class="form-control cabin-select" required>
                    <option value="">请选择</option>
                    <option value="1">经济舱</option>
                    <option value="2">商务舱</option>
                    <option value="3">头等舱</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">座位号</label>
                <select name="passengers[${index}].seatNo" class="form-control seat-select" required>
                    <option value="">请选择座位</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">金额</label>
                <input type="text" name="passengers[${index}].amount" class="form-control amount-input" readonly>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-danger w-100 btn-remove">🗑 删除</button>
            </div>
        </div>
    `;
        container.appendChild(block);
        updateTotalAmount();
    }

    document.getElementById('addPassengerBtn').addEventListener('click', addPassengerBlock);

    document.getElementById('passengerContainer').addEventListener('change', function (e) {
        if (e.target.classList.contains('cabin-select')) {
            const block = e.target.closest('.passenger-block');
            const cabin = e.target.value;
            updateTotalAmount();

            // 清除之前选的座位
            const seatSelect = block.querySelector('.seat-select');
            const oldSelectedSeat = seatSelect.value;
            if (oldSelectedSeat) {
                selectedSeats.delete(oldSelectedSeat);
                seatSelect.value = "";
            }

            fetchAvailableSeats(cabin, block);
            refreshAllSeatOptions();
        }

        if (e.target.classList.contains('seat-select')) {
            const seatSelect = e.target;

            // 移除旧选中的座位（如果有）
            let previousSelectedSeat = seatSelect.getAttribute('data-prev-seat');
            if (previousSelectedSeat) {
                selectedSeats.delete(previousSelectedSeat);
            }

            const newSeat = seatSelect.value;
            if (newSeat) {
                selectedSeats.add(newSeat);
                seatSelect.setAttribute('data-prev-seat', newSeat);
            } else {
                seatSelect.removeAttribute('data-prev-seat');
            }

            refreshAllSeatOptions();
        }
    });

    document.getElementById('passengerContainer').addEventListener('click', function (e) {
        if (e.target.classList.contains('btn-remove')) {
            const block = e.target.closest('.passenger-block');
            const seatSelect = block.querySelector('.seat-select');
            const seat = seatSelect.value;
            if (seat) {
                selectedSeats.delete(seat);
            }
            block.remove();
            updateTotalAmount();
            refreshAllSeatOptions();
        }
    });

    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('orderNo').value = generateOrderNo();
        addPassengerBlock();
    });
    // 表单提交拦截，使用AJAX
    // ✅ 修改 JS 中的跳转逻辑
    document.getElementById('orderForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);

        fetch('/order/submit', {
            method: 'POST',
            body: formData
        })
            .then(res => {
                if (res.ok) {
                    alert("订单提交成功！");
                    // ✅ 读取跳转参数
                    const departureCity=document.getElementById('departureCity')?.value||'';
                    const arrivalCity=document.getElementById('arrivalCity')?.value||'';
                    const departureDate=document.getElementById('departureDate')?.value||'';
                    const returnDate=document.getElementById('returnDate')?.value||'';
                    const roundTrip = document.getElementById('roundTrip')?.value||'';
                    const outPage = 1;
                    const returnPage = 1;
                    console.log("参数值", {departureCity, arrivalCity, departureDate, returnDate, roundTrip, outPage, returnPage})
                    const redirectUrl = `/planeTicket/search?departureCity=${departureCity}&arrivalCity=${arrivalCity}&departureDate=${departureDate}&returnDate=${returnDate}&roundTrip=${roundTrip}&outPage=${outPage}&returnPage=${returnPage}`;

                    window.location.href = redirectUrl;
                } else {
                    alert("提交失败，请重试！");
                }
            })
            .catch(error => {
                console.error("提交异常：", error);
                alert("提交异常，请稍后重试！");
            });
    });


</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
